package com.dobby.pea.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dobby.pea.common.R;
import com.dobby.pea.dto.GoodDto;
import com.dobby.pea.dto.ShoppingCartDto;
import com.dobby.pea.entity.*;
import com.dobby.pea.mapper.ShoppingCartMapper;
import com.dobby.pea.service.GoodService;
import com.dobby.pea.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dobby.pea.service.ShoppingCartService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, tbShoppingCart> implements ShoppingCartService {

    @Autowired
    private GoodService goodService;

    @Autowired
    private UserService userService;

    @Transactional
    public R<Page> ShoppingCartDtoPage(int page, int pageSize,Long UserId) {
        log.info( "page,  pageSize, UserId----------->{},{},{}",page,pageSize,UserId);
        //构造分页构造器对象
        Page<tbShoppingCart> shoppingCartPage = new Page<>(page,pageSize);
        Page<ShoppingCartDto> shoppingCartDtoPage = new Page<>();

        LambdaQueryWrapper<tbShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(tbShoppingCart::getUserId,UserId);
        queryWrapper.orderByDesc(tbShoppingCart::getCreateTime);

        //执行分页查询
        this.page(shoppingCartPage,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(shoppingCartPage,shoppingCartDtoPage,"records");


        List<tbShoppingCart> records = shoppingCartPage.getRecords();
        List<ShoppingCartDto> list = records.stream().map((item) -> {
            ShoppingCartDto shoppingCartDto = new ShoppingCartDto();

            BeanUtils.copyProperties(item,shoppingCartDto);

            Long goodId = item.getGoodId();
            Long userId = item.getUserId();
            //根据id查询商品对象
            tbGood good = goodService.getById(goodId);
            tbUser user = userService.getById(userId);


            shoppingCartDto.setGood(good);
            shoppingCartDto.setUser(user);

            return shoppingCartDto;
        }).collect(Collectors.toList());

        shoppingCartDtoPage.setRecords(list);

        return R.success(shoppingCartDtoPage);

    }

}
